package com.hjieli.config.security;


import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.hjieli.config.security.provider.UsernamePasswordAuthenticationProvider;
import com.hjieli.config.security.provider.WeixinMpAuthenticationProvider;
import com.hjieli.config.security.util.MD5PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Resource
    private DataSource dataSource;
	
	@Autowired
    private PasswordEncoder passwordEncoder;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// TODO Auto-generated method stub

		 //inMemoryAuthentication 从内存中获取
		//		  auth.inMemoryAuthentication()
		//		  .passwordEncoder(new BCryptPasswordEncoder())
		//		  .withUser("user")
		//		  .password(new BCryptPasswordEncoder().encode("123"))
		//		  .roles("admin");
		
		
		//从数据库读取
//	  auth.jdbcAuthentication()
//		  .dataSource(dataSource)
//          .usersByUsernameQuery("SELECT account,password,is_enable FROM sys_user_info WHERE account = ?")
//          .authoritiesByUsernameQuery( 
//          		"SELECT sys_user_info.account,sys_role_info.role_tag FROM sys_user_info INNER JOIN sys_user_x_role ON sys_user_info.id = sys_user_x_role.user_id " + 
//          		"LEFT JOIN sys_role_info ON sys_user_x_role.role_id = sys_role_info.id " + 
//          		"WHERE sys_user_info.account = ? ")
//          .passwordEncoder(passwordEncoder);

		 auth
         	.authenticationProvider(usernamePasswordAuthenticationProvider())
         	.authenticationProvider(weixinMpAuthenticationProvider());
	}
	
	@Override
    protected void configure(HttpSecurity http) throws Exception {
         //定义访问权限规则
		
        http
        	.authorizeRequests()
                .antMatchers(
                		"/login",
                		"/wxlogin",
                		"/api/weixin/authorize",
                		"/api/weixin/getOpenId",
                		"/api/weixin/getJsConfig",
                		"/api/carInfo/info",
                		"/error/**").permitAll()
                .antMatchers("/admin/**").hasRole("SUPER_MGR")
                .antMatchers("/api/**").hasAnyRole("SUPER_MGR,USER,DATA_MGR")
                .and().formLogin().loginPage("/login").successForwardUrl("/admin/index").failureForwardUrl("/login");
      
        http.headers().frameOptions().disable();
        
    }
	

    @Bean
    public UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider() {
        return new UsernamePasswordAuthenticationProvider();
    }

    @Bean
    public WeixinMpAuthenticationProvider weixinMpAuthenticationProvider() {
        return new WeixinMpAuthenticationProvider();
    }
	
	@Bean
	@Override
	protected AuthenticationManager authenticationManager() throws Exception {
		// TODO Auto-generated method stub
		return super.authenticationManager();
	}

	@Bean
	@Override
	protected UserDetailsService userDetailsService() {
		// TODO Auto-generated method stub
		return super.userDetailsService();
	}

//	@Bean
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder(); //指定4-31位的长度
//    }

	@Bean
    public PasswordEncoder passwordEncoder() {
        return new MD5PasswordEncoder();
    }
	
	public static void main(String[] args) {
		 String pwd = "123";
	        String encodePwd = BCrypt.hashpw(pwd, BCrypt.gensalt()); // 加密，核心代码
	        System.out.println(encodePwd);
	}


	
}
